package com.vrv.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.vrv.entity.AdminInfo;
import com.vrv.entity.DbInfo;
import com.vrv.entity.UserInfo;
import com.vrv.utils.Constans;
import com.vrv.utils.HttpClientUtil;
import com.vrv.utils.JsonUtil;
import com.vrv.utils.MD5Util;
import com.vrv.utils.SystemConfig;
import com.vrv.utils.XMLRead;

@Controller
public class LoginController {

    private static final Logger log = Logger.getLogger(LoginController.class);

    @Autowired
    HttpServletRequest request;

    @RequestMapping("/toLogin")
    public String toLogin() {
        if (StringUtils.isEmpty(XMLRead.xmlDbInfo().getCaseAim())) {
            return "dbIndex";
        }
        return "login";
    }

    @RequestMapping("/logout")
    public String logout() {
        request.getSession().setAttribute("userInfo", null);
        request.getSession().setAttribute("type", null);
        return "redirect:/toLogin";
    }

    @RequestMapping(value = "/loginByHttpClient", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String loginByHttpClient(HttpServletRequest request, String account, String password,
            String tableName, Integer type) {
        HttpSession session = request.getSession();
        if (type == 2) {
            session.setAttribute("type", 2);
            session.setAttribute("userInfo", new UserInfo());
            return "true";
        }

        String userStr = getStr(account, password, tableName);
        System.out.println(userStr);
        Map<String, Object> map = JsonUtil.parseJSON2Map(userStr);
        if (JsonUtil.parseJSON2Map(map.get("result").toString()).containsKey("content")) {
            JSONArray jsonArray = JSONArray.fromObject(JsonUtil.parseJSON2Map(
                    map.get("result").toString()).get("content"));
            List<Object> a = JsonUtil.jsonToList(jsonArray.toString());
            if (type == 0) {
                UserInfo userInfo = JsonUtil.jsonToBean(a.get(0).toString(), UserInfo.class);
                session.setAttribute("userInfo", userInfo);
                session.setAttribute("type", 0);
            } else {
                AdminInfo userInfo = JsonUtil.jsonToBean(a.get(0).toString(), AdminInfo.class);
                session.setAttribute("userInfo", userInfo);
                session.setAttribute("type", 1);
            }
        } else {
            userStr = "false";
        }
        return userStr;
    }

    public String getStr(String account, String password, String tableName) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("target", XMLRead.AIM);
        params.put("option", "select_table");
        params.put("service", "all");
        params.put("object", "table");

        Map<String, Object> dbinfoMap = new HashMap<String, Object>();
        DbInfo dbInfo = XMLRead.xmlDbInfo();
        dbinfoMap.put("type", dbInfo.getType());
        dbinfoMap.put("ip", dbInfo.getIp());
        dbinfoMap.put("port", dbInfo.getPort());
        dbinfoMap.put("dbname", dbInfo.getDbname());
        dbinfoMap.put("user", dbInfo.getUser());
        dbinfoMap.put("passwd", dbInfo.getPassword());
        Map<String, Object> datebaseinfo = new HashMap<String, Object>();
        datebaseinfo.put("dbinfo", dbinfoMap);

        params.put("datebaseinfo", datebaseinfo);

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> paramsCell = new HashMap<String, Object>();
        paramsCell.put("name", tableName);
        paramsCell.put("asname", "");
        mapList.add(paramsCell);
        Map<String, Object> tableInfoMap = new HashMap<String, Object>();
        tableInfoMap.put("tables", mapList);
        tableInfoMap.put("from", 0);
        tableInfoMap.put("count", 10);

        List<Map<String, Object>> mapList2 = new ArrayList<Map<String, Object>>();
        Map<String, Object> paramsCell2 = new HashMap<String, Object>();
        paramsCell2.put("name", "*");
        paramsCell2.put("asname", "");
        mapList2.add(paramsCell2);
        tableInfoMap.put("cols", mapList2);
        List<Map<String, Object>> mapList3 = new ArrayList<Map<String, Object>>();

        Map<String, Object> paramsObj3 = new HashMap<String, Object>();
        paramsObj3.put("account", account);
        Map<String, Object> paramsObj4 = new HashMap<String, Object>();
        paramsObj4.put("term", paramsObj3);
        mapList3.add(paramsObj4);

        Map<String, Object> paramsObj7 = new HashMap<String, Object>();
        paramsObj7.put("password", MD5Util.MD5(password));
        Map<String, Object> paramsObj8 = new HashMap<String, Object>();
        paramsObj8.put("term", paramsObj7);
        mapList3.add(paramsObj8);

        Map<String, Object> paramsObj5 = new HashMap<String, Object>();
        paramsObj5.put("must", mapList3);
        Map<String, Object> paramsObj6 = new HashMap<String, Object>();
        paramsObj6.put("bool", paramsObj5);

        tableInfoMap.put("where", paramsObj6);

        params.put("tableinfo", tableInfoMap);
        String json = JsonUtil.MapToJson(params);
        String str = HttpClientUtil.getInstance().post(
                "http://" + XMLRead.AIM + ":56790/?localservice", json);
        return str;
    }

    @RequestMapping(value = "/addDB", produces = Constans.PRODUCES)
    @ResponseBody
    public String addDb(DbInfo dbInfo) {
        String msg = "true";

        Map<String, Object> dbinfoMap = new HashMap<String, Object>();
        dbinfoMap.put("type", dbInfo.getType());
        dbinfoMap.put("ip", dbInfo.getIp());
        dbinfoMap.put("port", dbInfo.getPort());
        dbinfoMap.put("dbname", dbInfo.getDbname());
        dbinfoMap.put("user", dbInfo.getUser());
        dbinfoMap.put("passwd", dbInfo.getPassword());

        Map<String, Object> datebaseinfo = new HashMap<String, Object>();
        datebaseinfo.put("dbinfo", dbinfoMap);

        // String requetIP = getRequestIP(request);
        String requetIP = SystemConfig.getStr("restful_ip");

        Map<String, Object> root = new HashMap<String, Object>();
        root.put("target", requetIP);
        root.put("option", "datebaseinfo");
        root.put("services", "all");
        root.put("object", "gettables");
        root.put("hostname", request.getRemoteUser());
        root.put("datebaseinfo", datebaseinfo);

        String result = HttpClientUtil.getInstance().post(
                "http://" + XMLRead.AIM + ":56790/?localservice", JsonUtil.MapToJson(root));
        Map<String, Object> rMap = null;
        if (!StringUtils.isEmpty(result)) {
            rMap = JsonUtil.parseJSON2Map(result);
        }
        if (null != rMap && "200".equals(String.valueOf(rMap.get("status")))) {
            try {
                String path = XMLRead.getFilepath();
                log.info("path:" + path);
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdir();
                }
                File file2 = new File(path + "bigDataConfig.xml");
                if (!file2.exists()) {
                    file2.createNewFile();
                } else {
                    file2.delete();
                }
                createDBInfo(dbInfo);
                XStream xstream = new XStream();
                xstream.alias("bigdata", DbInfo.class);

                FileOutputStream o = new FileOutputStream(file2);
                xstream.toXML(dbInfo, o);
            } catch (IOException e) {
                log.error(e.getMessage());
                msg = "文件创建失败，请检查目录权限";
            }
        } else {
            msg = "数据库配置信息不正确";
        }

        return msg;
    }

    @RequestMapping("/test")
    @ResponseBody
    public String name() {
        return XMLRead.getFilepath();
    }

    private void createDBInfo(DbInfo dbInfo) {
        dbInfo.setCaseAim(XMLRead.AIM);
    }
}